from celery import shared_task
from .models import Goods, Order
from django.db import transaction
import datetime


@shared_task()
@transaction.atomic
def seckill_goods():
    while True:
        # 锁住查询到的book对象，直到事务结束
        sid = transaction.savepoint()
        goods = Goods.objects.filter(pk=1).first()  # 没加锁
        count = goods.store
        print('现在的库存为：%s' % count)
        if goods.store > 0:
            print('库存可以，下单')
            Order.objects.create(order_id=str(datetime.datetime.now()), order_name='测试订单-乐观锁')
            # 库存-1，扣减的时候，判断库存是不是上面查出来的库存，如果不是，就回滚
            # time.sleep(random.randint(1, 4))  # 模拟延迟
            res = Goods.objects.filter(pk=1, store=count).update(store=count - 1)
            if res >= 1:  # 表示修改成功
                transaction.savepoint_commit(sid)
                print('秒杀成功')
                return '秒杀成功'
            else:  # 修改不成功，回滚
                transaction.savepoint_rollback(sid)
                print('秒杀失败')
                continue

        else:
            transaction.savepoint_rollback(sid)
            print('123')
            return '库存不足，秒杀失败'
